import React, { Component } from "react";
import { Card, Form, Input, Checkbox, Button, message } from "antd";
import logo from "assets/logo.png";
import "./index.css";
import { loginAPI } from "api/login";

export default class Login extends Component {
  submitData = async (values) => {
    try {
      console.log(values);
      const res = await loginAPI(values);
      console.log(res);
      localStorage.setItem("geek-pc", res.data.data.token);
      this.props.history.push("/layout");
      message.success("登录成功", 1);
    } catch (error) {
      console.dir(error);
      message.error(error.response.data.message, 1);
    }
  };
  render() {
    return (
      <div className="login">
        <Card className="login-container">
          <img className="login-logo" src={logo} alt="" />
          <Form
            name="basic"
            size="large"
            onFinish={this.submitData}
            initialValues={{
              mobile: "13911111111",
              code: "246810",
              agree: true,
            }}
          >
            <Form.Item
              name="mobile"
              rules={[
                {
                  required: true,
                  message: "手机号不能为空",
                },
                {
                  pattern: /^1[3-9]\d{9}$/,
                  message: "请输入正确的手机号",
                },
              ]}
            >
              <Input placeholder="手机号" />
            </Form.Item>

            <Form.Item
              name="code"
              rules={[
                {
                  required: true,
                  message: "请输入验证码",
                },
                { pattern: /^\d{6}$/, message: "验证码格式错误" },
              ]}
            >
              <Input.Password placeholder="验证码" />
            </Form.Item>

            <Form.Item
              valuePropName="checked"
              name="agree"
              rules={[
                {
                  validator: (_, value) => {
                    if (value === true) {
                      return Promise.resolve();
                    } else {
                      return Promise.reject("请确保阅读并同意用户协议");
                    }
                  },
                },
              ]}
            >
              <Checkbox>我已阅读并同意[隐私条款]和[用户协议]</Checkbox>
            </Form.Item>

            <Form.Item>
              <Button type="primary" htmlType="submit" block>
                登录
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    );
  }
}
